package com.hisense.ovcloud.commons.configs.filters;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.util.Objects;

@Component
@Slf4j
@Order(-1100)
public class ELBHealthCheckerFilter implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {

        // 根据条件判断是否直接返回
        if (exchange.getRequest().getHeaders().containsKey("User-Agent") &&
                Objects.requireNonNull(exchange.getRequest().getHeaders().getFirst("User-Agent")).contains("ELB-HealthChecker/2.0")) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.OK);
            // 可以设置更多响应属性，例如：response.getHeaders().setContentType(MediaType.TEXT_PLAIN);
            return response.writeWith(Mono.just(exchange.getResponse().bufferFactory().wrap("".getBytes())));
        }

        // 继续执行其他的过滤器或处理请求
        return chain.filter(exchange);
    }
}
